package com.young.app.mapper;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.young.app.dto.PersonDTO;
import com.young.app.model.HomeAddress;
import com.young.app.pojo.PersonDO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.io.IOException;

/**
 * MapStruct mapper
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/8/10
 */
@Mapper
public interface PersonConverter {
    ObjectMapper objectMapper = new ObjectMapper();
    PersonConverter INSTANCE = Mappers.getMapper(PersonConverter.class);

    /**
     * 类型转换方法
     * {@link PersonDO} 转 {@link PersonDTO}
     *
     * @param do2dto
     * @return
     */
    @Mapping(source = "name", target = "userName")
    @Mapping(target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "address", expression = "java(homeAddressToObject(do2dto.getAddress()))")
    PersonDTO do2dto(PersonDO do2dto);

    /**
     * {@link PersonDTO} 转  {@link PersonDO}
     *
     * @param dto2do
     * @return
     */
    @Mapping(source = "userName", target = "name")
    @Mapping(target = "address", expression = "java(homeAddressToString(dto2do.getAddress()))")
    PersonDO dto2do(PersonDTO dto2do);

    /**
     * {@link String}转{@link HomeAddress}
     *
     * @param address
     * @return
     * @throws IOException
     */
    default HomeAddress homeAddressToObject(String address) {
        try {
            return objectMapper.readValue(address, HomeAddress.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * {@link HomeAddress}转{@link String}
     *
     * @param address
     * @return
     */
    default String homeAddressToString(HomeAddress address) {
        return JSON.toJSONString(address);
    }
}